﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SqlScriptVault.Model
{
    [Serializable]
    public class ScriptVaultExecution
    {
        private readonly Dictionary<Script, ScriptExecution> _scriptExecutions;

        public ScriptVaultExecution(ServerGroup serverGroup, IList<string> serverTypes)
        {
            ServerGroup = serverGroup;
            ServerTypes = serverTypes;

            _scriptExecutions = new Dictionary<Script, ScriptExecution>();
        }

        public ServerGroup ServerGroup { get; private set; }

        public IList<string> ServerTypes { get; private set; }

        public ICollection<ScriptProgress> Progress
        {
            get
            {
                return (from scriptExecution in _scriptExecutions
                        select new ScriptProgress
                        {
                            ImageName = scriptExecution.Value.Success.HasValue
                                        ? scriptExecution.Value.Success.Value
                                            ? "../Images/green-check-icon.png"
                                            : "../Images/red-cross-icon.png"
                                            : "../Images/Button-Play-icon.png",
                            Number = scriptExecution.Key.Number,
                            ScriptName = scriptExecution.Key.ScriptName,
                            Message = scriptExecution.Value.Message
                        }).ToList();
            }
        }

        public IEnumerable<Script> Scripts
        {
            get
            {
                return _scriptExecutions.Keys;
            }
        }

        public void AddScript(Script script)
        {
            _scriptExecutions.Add(script, new ScriptExecution());
        }

        public void ScriptSucceeded(Script script)
        {
            _scriptExecutions[script].Success = true;
            _scriptExecutions[script].ExecutionDateTime = DateTime.Now;
        }

        public void ScriptFailed(Script script, string message)
        {
            _scriptExecutions[script].Success = false;
            _scriptExecutions[script].ExecutionDateTime = DateTime.Now;
            _scriptExecutions[script].Message = message;
        }

        public bool AllSucceeded
        {
            get
            {
                return !_scriptExecutions.Values.Any(p => p.Success == false);
            }
        }

        public string FailureMessage
        {
            get
            {
                ScriptExecution failedScriptExecution = _scriptExecutions.Values.Where(execution => !execution.Success.Value).FirstOrDefault();
                return failedScriptExecution == null ? string.Empty : failedScriptExecution.Message;
            }
        }
    }
}
